package com.wing.purchase.service;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.enums.ProductEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.product.model.entity.ProductItem;
import com.wing.purchase.dao.PurQualityTestingTaskDao;
import com.wing.purchase.model.entity.PurQualityTestingTask;
import com.wing.purchase.model.entity.PurQualityTestingTaskDetail;
import com.wing.purchase.model.entity.PurQualityTestingTaskDetailValue;
import com.wing.purchase.model.request.QualityDetectionInfoForm;
import com.wing.purchase.model.response.PurQualityTestingTaskDetailVo;
import com.wing.purchase.model.response.QualityTimeDetailInfoVo;
import com.wing.user.feign.UserClient;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 采购-质检任务-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class PurQualityTestingTaskServiceImpl extends ServiceImpl<PurQualityTestingTaskDao, PurQualityTestingTask> implements PurQualityTestingTaskService {

    @Resource
    private PurQualityTestingTaskDetailService purQualityTestingTaskDetailService;

    @Resource
    private PurQualityTestingTaskDetailValueService purQualityTestingTaskDetailValueService;

    @Resource
    private UserClient userClient;

    /**
     * 查询所有的质检任务
     * @param pg 分页参数
     * @param params 参数
     * @return 分页后的质检任务
     */
    @Override
    public IPage<PurQualityTestingTask> pageList4app(Page<PurQualityTestingTask> pg, Map<String, Object> params) {
        List<PurQualityTestingTask> taskList = this.baseMapper.pageList4app(pg,params);
        pg.setRecords(taskList);
        return pg;
    }

    /**
     * 添加质检任务
     * @param purQualityTestingTask 质检任务入参
     * @return 是否添加成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addQualityTestingTask(PurQualityTestingTask purQualityTestingTask) {
        //添加质检任务
        String taskNo = UniqueIdGeneratorUtil.generateUniqueId("IQC", "yyyyMMdd", 1000, 9999);
        purQualityTestingTask.setCode(taskNo);
        //状态:inspect(0,送检中);finish(1,完成);confirm(2,待认领);close(3,关闭)
        purQualityTestingTask.setStatus(String.valueOf(MaintenanceEnum.QualityStatus.DRL.getCode()));
        purQualityTestingTask.setCreateTime(LocalDateTime.now());
        purQualityTestingTask.setUpdateTime(LocalDateTime.now());
        purQualityTestingTask.setCreator(JwtUtils.getLoginUserId());
        purQualityTestingTask.setCreatorName(JwtUtils.getLoginUsername());
        purQualityTestingTask.setSubmitPostId(JwtUtils.getPostId());
        purQualityTestingTask.setSubmitDepId(JwtUtils.getDepartmentId());
        boolean save = this.save(purQualityTestingTask);
        if(save) {
            List<PurQualityTestingTaskDetail> lists = new ArrayList<>();
            for (int i = 1; i <= purQualityTestingTask.getSubmissionQuantity(); i++) {
                //添加质检详情
                PurQualityTestingTaskDetail taskDetail = new PurQualityTestingTaskDetail();
                taskDetail.setQualityTestingTaskId(purQualityTestingTask.getId());
                taskDetail.setCode(taskNo+"-"+i);
                //待检测
                taskDetail.setStatus(ProductEnum.qualityStatusEmum.DJC.getCode());
                taskDetail.setCreateTime(LocalDateTime.now());
                taskDetail.setCreator(JwtUtils.getLoginUserId());
                taskDetail.setCreatorName(JwtUtils.getLoginUsername());
                lists.add(taskDetail);
            }
            boolean saved = this.purQualityTestingTaskDetailService.saveBatch(lists);
            if (saved){
                return 1;
            }else{
                return 0;
            }
        }
        return 0;
    }

    /**
     * 查询质检详情
     * @param taskId 任务详情
     * @return
     */
    @Override
    public PurQualityTestingTaskDetailVo detail(String taskId) {
        //1. 查询质检详情
        PurQualityTestingTaskDetailVo detailVo = this.baseMapper.getDetailVoInfoBy(taskId);

        //部门 / 岗位
        JsonResult<List<Map<String, String>>> roleAllMap = userClient.getRoleAllMap();
        List<Map<String, String>> roles = new ArrayList<>();
        if (roleAllMap.getCode() == 200) {
            roles = roleAllMap.getData();
        }

        //3.补充时间线
        QualityTimeDetailInfoVo infoVo = baseMapper.getTimeInfo(taskId);
        //4. 判断状态
        if (detailVo.getStatus().equals(String.valueOf(MaintenanceEnum.QualityStatus.WC.getCode()))) {
            QualityTimeDetailInfoVo finshInfo = baseMapper.selectLastDetailFinshInfo(Long.valueOf(taskId));
            infoVo.setCheckDepName(finshInfo.getCheckDepName());
            infoVo.setCheckTime(finshInfo.getCheckTime());
            infoVo.setCheckName(finshInfo.getCheckName());
            infoVo.setCheckPostName(finshInfo.getCheckPostName());
        }
        if (StrUtil.isNotEmpty(infoVo.getCreateTime())) {
            infoVo.setCreateTime("(" + infoVo.getCreateTime() + ")");
        }
        if (StrUtil.isNotEmpty(infoVo.getGetTime())) {
            infoVo.setGetTime("(" + infoVo.getGetTime() + ")");
        }
        if (StrUtil.isNotEmpty(infoVo.getCheckTime())) {
            infoVo.setCheckTime("(" + infoVo.getCheckTime() + ")");
        }


        for (Map<String, String> role : roles) {
            if (StringUtils.isNotBlank(infoVo.getCreatePostName())) {
                if (role.get("id").equals(infoVo.getCreatePostName())) {
                    infoVo.setCreatePostName(role.get("name"));
                }
            }
            if (StringUtils.isNotBlank(infoVo.getGetPostName())) {
                if (role.get("id").equals(infoVo.getGetPostName())) {
                    infoVo.setGetPostName(role.get("name"));
                }
            }
            if (StringUtils.isNotBlank(infoVo.getCheckPostName())) {
                if (role.get("id").equals(infoVo.getCheckPostName())) {
                    infoVo.setCheckPostName(role.get("name"));
                }
            }
            if (StringUtils.isNotBlank(infoVo.getCreateDepName())) {
                if (role.get("id").equals(infoVo.getCreateDepName())) {
                    infoVo.setCreateDepName(role.get("name"));
                }
            }
            if (StringUtils.isNotBlank(infoVo.getGetDepName())) {
                if (role.get("id").equals(infoVo.getGetDepName())) {
                    infoVo.setGetDepName(role.get("name"));
                }
            }
            if (StringUtils.isNotBlank(infoVo.getCheckDepName())) {
                if (role.get("id").equals(infoVo.getCheckDepName())) {
                    infoVo.setCheckDepName(role.get("name"));
                }
            }
        }

        detailVo.setInfoVo(infoVo);

        if (ObjectUtil.isNotEmpty(detailVo)){
            //查看
            detailVo.setSourceTypeName(ProductEnum.purSourceTypeEmum.getNameByCode(detailVo.getSourceType()));
            //2. 查询质检详情列表
            QueryWrapper<PurQualityTestingTaskDetail> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("quality_testing_task_id", taskId);
            detailQueryWrapper.eq("is_deleted",false);
            List<PurQualityTestingTaskDetail> list = this.purQualityTestingTaskDetailService.list(detailQueryWrapper);
            if (ObjectUtil.isNotEmpty(list)){
                //任务明细
                for (PurQualityTestingTaskDetail taskDetail : list) {
                    //处理方式
                    taskDetail.setDealWayName(ProductEnum.dealWayEmum.getNameByCode(taskDetail.getDealWay()));
                    taskDetail.setStatusName(ProductEnum.qualityStatusEmum.getNameByCode(taskDetail.getStatus()));
                    //是否合格
                    if (StrUtil.isNotEmpty(taskDetail.getQualityTestingResult())){
                        taskDetail.setQualityTestingResultName(ProductEnum.qualityResultNameEmum.getNameByCode(taskDetail.getQualityTestingResult()));
                    }else{
                        taskDetail.setQualityTestingResultName("");
                    }
                    //查询质检项详情
                    QueryWrapper<PurQualityTestingTaskDetailValue> detailValueQueryWrapper = new QueryWrapper<>();
                    detailValueQueryWrapper.eq("testing_task_detail_id", taskDetail.getId());
                    detailValueQueryWrapper.eq("is_deleted", false);
                    List<PurQualityTestingTaskDetailValue> detailValues = this.purQualityTestingTaskDetailValueService.list(detailValueQueryWrapper);
                    taskDetail.setDetailValues(detailValues);
                }
            }
            detailVo.setTaskDetailList(list);
        }
        return detailVo;
    }

    /**
     * 认领质检任务
     * @param recordId 任务id
     * @return >0 认领成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int claim(String recordId) {
        //1. 修改质检任务
        PurQualityTestingTask byId = this.getById(recordId);
        byId.setGetId(JwtUtils.getLoginUserId());
        byId.setGetTime(LocalDateTime.now());
        byId.setGetName(JwtUtils.getLoginUsername());
        byId.setUpdateTime(LocalDateTime.now());
        byId.setModifier(JwtUtils.getLoginUserId());
        byId.setModifierName(JwtUtils.getLoginUsername());
        byId.setGetPostId(JwtUtils.getPostId());
        byId.setGetDepId(JwtUtils.getDepartmentId());
        //修改状态为送检中
        byId.setStatus(String.valueOf(MaintenanceEnum.QualityStatus.SJZ.getCode()));
        boolean updated = this.updateById(byId);
        if (updated){
            //查询 质检项目
            QueryWrapper<PurQualityTestingTaskDetail> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("quality_testing_task_id", recordId);
            detailQueryWrapper.eq("is_deleted",false);
            List<PurQualityTestingTaskDetail> list = this.purQualityTestingTaskDetailService.list(detailQueryWrapper);

            Long productDetailId = byId.getProductDetailId();
            if (ObjectUtil.isNotEmpty(productDetailId)){
                //IQC 默认1
                String IQC= byId.getQualityTestingTypeId() == null ? "1":byId.getQualityTestingTypeId().toString();
                //查询物料的质检项目 所有质检项都是一样的
                List<ProductItem> items = this.purQualityTestingTaskDetailService.getQualityInfoBy(productDetailId,IQC,byId.getQualityTestingCategoryId());
                //生成质检项
                if (CollectionUtil.isNotEmpty(list) && CollectionUtil.isNotEmpty(items)){
                    List<PurQualityTestingTaskDetailValue> listValue = new ArrayList<>();
                    for (PurQualityTestingTaskDetail taskDetail : list) {
                        for (ProductItem item : items) {
                            //初始化质检信息
                            PurQualityTestingTaskDetailValue value = new PurQualityTestingTaskDetailValue();
                            value.setTestingTaskDetailId(taskDetail.getId());
                            value.setQualityId(item.getId());
                            value.setQualityName(item.getName());
                            value.setStandard("暂无");
                            value.setUtensil(item.getTestTool());
                            value.setWay(item.getTestMethod());
                            value.setNo(item.getCode());
                            value.setItemType(item.getItemType());
                            value.setImportance(item.getImportanceCode());
                            value.setCreateTime(LocalDateTime.now());
                            value.setCreator(JwtUtils.getLoginUserId());
                            value.setCreatorName(JwtUtils.getLoginUsername());
                            listValue.add(value);
                        }
                    }
                    if (CollectionUtil.isNotEmpty(listValue)){
                        boolean saved = this.purQualityTestingTaskDetailValueService.saveBatch(listValue);
                        if (saved){
                            return 1;
                        }
                    }
                }
            }

        }
        return 1;
    }

    /**
     * 检测
     * @param qualityDetectionInfoForm 检测入参
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int detection(QualityDetectionInfoForm qualityDetectionInfoForm) {
        //查询recordDetail信息
        Long taskDetailId = qualityDetectionInfoForm.getTaskDetailId();
        PurQualityTestingTaskDetail taskDetail = this.purQualityTestingTaskDetailService.getById(taskDetailId);
        //任务id
        Long qualityTestingTaskId = taskDetail.getQualityTestingTaskId();
        PurQualityTestingTask task = this.getById(qualityTestingTaskId);
        if (ObjectUtil.isNotEmpty(qualityDetectionInfoForm.getQualityTestingResult())
                && qualityDetectionInfoForm.getQualityTestingResult().equals(ProductEnum.qualityResultNameEmum.HG.getCode())){
            //合格数 + 1
            task.setOkQuantity(task.getOkQuantity() + 1 );
        }else if (ObjectUtil.isNotEmpty(qualityDetectionInfoForm.getQualityTestingResult())
                && qualityDetectionInfoForm.getQualityTestingResult().equals(ProductEnum.qualityResultNameEmum.BHG.getCode())){
            //不合格数 + 1
            task.setNotQuantity(task.getNotQuantity() + 1 );
            //判断处理方式
            if (StrUtil.isNotEmpty(qualityDetectionInfoForm.getDealWay()) && "1".equals(qualityDetectionInfoForm.getDealWay())){
                //返修
                task.setReturnQuantity(task.getReturnQuantity() + 1 );
            }
            else if(StrUtil.isNotEmpty(qualityDetectionInfoForm.getDealWay()) && "1".equals(qualityDetectionInfoForm.getDealWay())){
                //报废
                task.setNgQuantity(task.getNgQuantity() + 1 );
            }
        }
        QueryWrapper<PurQualityTestingTaskDetail> detailQueryWrapper = new QueryWrapper<>();
        detailQueryWrapper.eq("quality_testing_task_id", task.getId());
        detailQueryWrapper.eq("is_deleted",false);
        int count = this.purQualityTestingTaskDetailService.count(detailQueryWrapper);
        if (count >= task.getSubmissionQuantity() - 1){
            task.setStatus(String.valueOf(MaintenanceEnum.QualityStatus.WC.getCode()));
        }
        //1. 修改任务信息
        boolean updated = this.updateById(task);
        if (updated){
            taskDetail.setQualityTestingResult(qualityDetectionInfoForm.getQualityTestingResult());
            taskDetail.setInspectDeviceCode(qualityDetectionInfoForm.getInspectDeviceCode());
            taskDetail.setCheckPostId(JwtUtils.getPostId());
            taskDetail.setCheckDepId(JwtUtils.getDepartmentId());
            taskDetail.setDealWay(qualityDetectionInfoForm.getDealWay());
            taskDetail.setPaperSlipPic(qualityDetectionInfoForm.getPaperSlipPic());
            taskDetail.setErrorResult(qualityDetectionInfoForm.getErrorResult());
            taskDetail.setCheckTime(LocalDateTime.now());
            taskDetail.setCheckUserId(JwtUtils.getLoginUserId());
            taskDetail.setCheckUserName(JwtUtils.getLoginUsername());
            taskDetail.setStatus(ProductEnum.qualityStatusEmum.YJC.getCode());
            taskDetail.setModifier(JwtUtils.getLoginUserId());
            taskDetail.setModifierName(JwtUtils.getLoginUsername());
            taskDetail.setUpdateTime(LocalDateTime.now());
            //2. 修改明细信息
            boolean taskDetailOk = this.purQualityTestingTaskDetailService.updateById(taskDetail);
            if (taskDetailOk){
                //3.修改质检项详情信息
                List<PurQualityTestingTaskDetailValue> detailValues = qualityDetectionInfoForm.getDetailValues();
                if (CollectionUtil.isNotEmpty(detailValues)){
                    for (PurQualityTestingTaskDetailValue detailValue : detailValues) {
                        detailValue.setModifier(JwtUtils.getLoginUserId());
                        detailValue.setModifierName(JwtUtils.getLoginUsername());
                        detailValue.setUpdateTime(LocalDateTime.now());
                    }
                    boolean updateBatchById = this.purQualityTestingTaskDetailValueService.updateBatchById(detailValues);
                    if (updateBatchById){
                        return 1;
                    }else{
                        return 0;
                    }
                }
            }
        }
        //判断检测是否合格
        return 1;
    }
}
